package com.codingke.codingbookstore.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bmob.pay.tool.BmobPay;
import com.bmob.pay.tool.PayListener;
import com.codingke.codingbookstore.R;
import com.codingke.codingbookstore.adapter.SettlementOrderListItemAdapter;
import com.codingke.codingbookstore.utils.AppUtils;
import com.codingke.codingbookstore.utils.Constant;
import com.codingke.codingbookstore.utils.NumberUtils;
import com.codingke.codingbookstore.vo.Address;
import com.codingke.codingbookstore.vo.Orders;
import com.codingke.codingbookstore.vo.User;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

public class SettlementActivity extends BaseActivity implements View.OnClickListener{

    private static final int GET_ADDRESS_REQUEST_CODE = 0x100;
    private RelativeLayout relativeLayout2_address;
    private Button button_payment;
    private TextView textView5_total_amount;
    private TextView textView4_username;
    private TextView textView4_phone;
    private TextView textView4_address;
    private RadioGroup radioGroup_pay;
    private ListView listView2_orders;
    private double totalAmount; //合计
    private ArrayList<Orders> orderList = new ArrayList<>();
    private Address userAddress;//用户地址
    private SettlementOrderListItemAdapter settlementOrderListItemAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settlement);
        Intent intent = getIntent();
        totalAmount = intent.getDoubleExtra("totalAmount",0); //订单总金额
        orderList = (ArrayList<Orders>) intent.getSerializableExtra("orderList");

        listView2_orders = (ListView) findViewById(R.id.listView2_orders);
        relativeLayout2_address = (RelativeLayout) findViewById(R.id.relativeLayout2_address);
        relativeLayout2_address.setOnClickListener(this);
        button_payment = (Button) findViewById(R.id.button_payment);
        button_payment.setOnClickListener(this);
        textView5_total_amount = (TextView) findViewById(R.id.textView5_total_amount);
        textView5_total_amount.setText("合计:"+NumberUtils.format(totalAmount)+"元");
        textView4_username = (TextView) findViewById(R.id.textView4_username);
        textView4_phone = (TextView) findViewById(R.id.textView4_phone);
        textView4_address = (TextView) findViewById(R.id.textView4_address);
        radioGroup_pay = (RadioGroup) findViewById(R.id.radioGroup_pay);
        //查询用户的收货地址
        queryAddress();
        //订单明细
        settlementOrderListItemAdapter = new SettlementOrderListItemAdapter(this,orderList);
        listView2_orders.setAdapter(settlementOrderListItemAdapter);
    }

    private void queryAddress() {
        User user = BmobUser.getCurrentUser(this,User.class);
        BmobQuery<Address> query = new BmobQuery<>();
        query.addWhereEqualTo("userId",user.getObjectId());
        query.order("-isDefault");
        query.findObjects(this, new FindListener<Address>() {
            @Override
            public void onSuccess(List<Address> list) {
                userAddress = list.get(0);
                updateAddressForUI();
            }
            @Override
            public void onError(int i, String s) {
                showToast("获取地址失败");
            }
        });
    }

    private void updateAddressForUI() {
        textView4_username.setText(userAddress.getUsername());
        textView4_phone.setText(userAddress.getPhoneNumber());
        textView4_address.setText(userAddress.getAddress());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.relativeLayout2_address:
                addressManager();
                break;
            case R.id.button_payment:
                payment();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (GET_ADDRESS_REQUEST_CODE==requestCode && RESULT_OK==resultCode){
            userAddress = (Address) data.getSerializableExtra("address");
            updateAddressForUI();
        }
    }

    //管理地址
    private void addressManager() {
        startActivityForResult(new Intent(this,SelectAddressActivity.class),GET_ADDRESS_REQUEST_CODE);
    }

    /**
     * 更新订单状态
     */
    private void updateOrders(){
        ArrayList<BmobObject> list = new ArrayList<>();
        for (int i=0;i<orderList.size();i++){
            Orders temp = orderList.get(i);
            temp.setOrderId(orderId);
            temp.setStatus(Constant.ORDER_PAYMENTS_RECEIVED);//设置为已付款
            temp.setBuyDate(AppUtils.getDate(new Date()));
            temp.setAddress(userAddress);
            temp.setFreight(0);//运费
            list.add(temp);
        }
        //批量更新订单状态
        new BmobObject().updateBatch(this, list, new UpdateListener() {
            @Override
            public void onSuccess() {
                finish();
            }

            @Override
            public void onFailure(int i, String s) {
                showToast("订单付款状态更新失败,请联系客服");
            }
        });
    }

    private String orderId;//付款订单编号


    private void payAli() {
       new BmobPay(SettlementActivity.this).pay(totalAmount, "购买图书订单", new PayListener() {
           @Override
           public void orderId(String s) {
               orderId = s;
           }
           @Override
           public void succeed() {
               showToast("付款成功");
               updateOrders();
           }
           @Override
           public void fail(int i, String s) {
               showToast("付款失败:"+s);
           }
           @Override
           public void unknow() {
               showToast("付款异常");
           }
       });
    }

    private void payWeixin() {
        new BmobPay(SettlementActivity.this).payByWX(totalAmount, "购买图书订单", new PayListener() {
            @Override
            public void orderId(String s) {
                orderId = s;
            }

            @Override
            public void succeed() {
                showToast("付款成功");
                updateOrders();
            }

            @Override
            public void fail(int code, String s) {
                //code为-3意味着没有安装BmobPlugin插件
                install(code);
            }

            @Override
            public void unknow() {
                showToast("付款异常");
            }
        });
    }


    private void payment() {
        if(userAddress==null){
            showToast("请选择收货地址");
            return;
        }
        //获取被选中的单选组件的ID
        int id = radioGroup_pay.getCheckedRadioButtonId();
        switch (id){
            case R.id.radioButton_alipay:
                payAli();
                break;
            case R.id.radioButton2_weixinpay:
                payWeixin();
        }
    }

    //安装
    private void install(int code) {
        if (code == -3) {
            new AlertDialog.Builder(SettlementActivity.this)
                    .setMessage(
                            "监测到你尚未安装支付插件,无法进行微信支付,请选择安装插件(已打包在本地,无流量消耗)还是用支付宝支付")
                    .setPositiveButton("安装",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(
                                        DialogInterface dialog,
                                        int which) {
                                    installBmobPayPlugin("BmobPayPlugin.apk");
                                }
                            })
                    .setNegativeButton("支付宝支付",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(
                                        DialogInterface dialog,
                                        int which) {
                                    payAli();
                                }
                            }).create().show();
        } else {
            Toast.makeText(SettlementActivity.this, "支付中断!",
                    Toast.LENGTH_SHORT).show();
        }
    }


    //安装插件
    private void installBmobPayPlugin(String fileName) {
        try {
            InputStream is = getAssets().open(fileName);
            File file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + fileName);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.parse("file://" + file),
                    "application/vnd.android.package-archive");
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
